package com.blobfish.fiction.common.util;

import cn.hutool.core.lang.Console;
import cn.hutool.db.nosql.redis.RedisDS;
import com.blobfish.fiction.common.DemoConfig;
import com.blobfish.fiction.common.model._MappingKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.CaseInsensitiveContainerFactory;
import com.jfinal.plugin.activerecord.dialect.OracleDialect;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.template.source.ClassPathSourceFactory;
import redis.clients.jedis.Jedis;

/**
 * 手动加载jfinal方法
 *
 * @author blobfish
 */
public class InitPluginUtil {
    private static InitPluginUtil initPluginUtil;
    private static Jedis jedis;

    private InitPluginUtil() {
        PropKit.use("a_little_config.txt");
    }

    public static InitPluginUtil getInstance() {
        if (initPluginUtil == null) {
            synchronized (InitPluginUtil.class) {
                if (initPluginUtil == null) {
                    initPluginUtil = new InitPluginUtil();
                }
            }
        }
        return initPluginUtil;
    }

    /**
     * 初始化数据库插件
     */
    public void initDatabasePlugin() {
        DruidPlugin druidPlugin = DemoConfig.createDruidPlugin();
        // 配置ActiveRecord插件
        ActiveRecordPlugin arp = new ActiveRecordPlugin(druidPlugin);
        arp.getEngine().setSourceFactory(new ClassPathSourceFactory());
        arp.addSqlTemplate("sql/all.sql");
        // 所有映射在 MappingKit 中自动化搞定
        _MappingKit.mapping(arp);
        druidPlugin.start();
        arp.start();
    }

    /**
     * 初始化oracle数据库插件
     */
    public void initOraclePlugin() {
        DruidPlugin druidPlugin = DemoConfig.createDruidPlugin();
        druidPlugin.setDriverClass("oracle.jdbc.driver.OracleDriver");
        // 配置ActiveRecord插件
        ActiveRecordPlugin arp = new ActiveRecordPlugin(druidPlugin);
        // 配置Oracle方言
        arp.setDialect(new OracleDialect());
        // 配置属性名(字段名)大小写不敏感容器工厂
        arp.setContainerFactory(new CaseInsensitiveContainerFactory());
        druidPlugin.start();
        arp.start();
    }

    public Jedis initRedisPlugin() {
        if (jedis == null) {
            synchronized (this) {
                if (jedis == null) {
                    jedis = RedisDS.create().getJedis();
                }
            }
        }
        return jedis;
    }



    public static void main(String[] args) {
        Jedis jedis = RedisDS.create().getJedis();
        Console.log(jedis.get("global:stationary"));
    }
}
